/*
 * AmazonAPIParser.java
 * 
 * Copyright 2012 Xinli Jia
 * 
 * Parsing the XML of item information returned by Amazon API
 */

package com.amazon.advertising.api;

import ie.dit.comp.lukejia.fyp.model.Item;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class AmazonAPIParser {
	private static final int NUM_OF_ITEMS = 5;

	public static List<Item> getItemInfo(String requestUrl) {
		List<Item> items = new ArrayList<Item>();

		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(requestUrl);
			NodeList list = doc.getElementsByTagName("Item");
			for (int i = 0; i < NUM_OF_ITEMS && i < list.getLength(); i++) {
				Item item;
				Node itemNode = list.item(i);
				String ASIN = itemNode.getFirstChild().getTextContent();
				Node attributesNode = itemNode.getLastChild();
				String title = attributesNode.getLastChild().getTextContent();
				// Remove information after left bracket
				if (title.contains("(")) {
					title = title.substring(0, title.indexOf(("(")));
					while (title.endsWith(" "))
						title = title.substring(0, title.length() - 1);
				}
				String url = itemNode.getChildNodes().item(2).getChildNodes()
						.item(5).getLastChild().getTextContent();
				item = new Item(title, ASIN, url);
				Node authorNode = attributesNode.getChildNodes().item(0);

				while (authorNode != null) {
					String tag = authorNode.getNodeName();
					if (tag.equals("Author") || tag.equals("Director")) {
						item.getAuthors().add(authorNode.getTextContent());
					} else if (tag.equals("Manufacturer")) {
						item.setManufacturer(authorNode.getTextContent());
					}
					authorNode = authorNode.getNextSibling();
				}

				items.add(item);
			}
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		return items;
	}
}
